﻿using ERP_SaaS_WinForm.生产计划_派单_车间;
using ERP_SaaS_WinForm.销售.Sales;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.销售
{
    /// <summary>
    /// 折扣方案添加窗体
    /// 用于为客户单价添加折扣方案，支持阶梯折扣选择
    /// </summary>
    public partial class AddDiscount : Form
    {
        #region 属性定义
        
        /// <summary>
        /// 客户单价ID - 关联的客户单价记录ID
        /// </summary>
        public int ClientPriceId { get; set; }
        
        /// <summary>
        /// 客户单价编号 - 客户单价的唯一编号
        /// </summary>
        public string ClientPriceCode { get; set; }
        
        /// <summary>
        /// 产品编码 - 关联的产品编码
        /// </summary>
        public string ProductCode { get; set; }
        
        /// <summary>
        /// 产品名称 - 关联的产品名称
        /// </summary>
        public string ProductName { get; set; }
        
        /// <summary>
        /// 产品规格型号 - 产品的规格型号信息
        /// </summary>
        public string Specification { get; set; }
        
        /// <summary>
        /// 总金额 - 订单的总金额
        /// </summary>
        public string TotalAmount { get; set; }
        
        /// <summary>
        /// 折扣方案名称 - 折扣方案的显示名称
        /// </summary>
        public string DiscountName {  get; set; }
        
        // 阶梯折扣相关属性
        /// <summary>
        /// 选中的阶梯折扣ID
        /// </summary>
        public int SelectedLadderId { get; set; }
        
        /// <summary>
        /// 选中的阶梯折扣规则
        /// </summary>
        public string SelectedLadderRule { get; set; }
        
        /// <summary>
        /// 选中的阶梯折扣明细（折扣率）
        /// </summary>
        public string SelectedLadderDetails { get; set; }
        
        #endregion

        /// <summary>
        /// 构造函数 - 初始化折扣方案添加窗体
        /// </summary>
        public AddDiscount()
        {
            InitializeComponent();
            
            // 绑定添加按钮事件
            if (btnAddClientPrice != null)
            {
                btnAddClientPrice.Click += btnAddDiscount_Click;
            }
            
            // 绑定产品选择按钮事件
            if (btnSelectProduct != null)
            {
                btnSelectProduct.Click += btnSelectProduct_Click;
            }
        }

        /// <summary>
        /// 窗体加载事件 - 初始化数据和加载阶梯折扣列表
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void AddDiscount_Load(object sender, EventArgs e)
        {
            // 调试：检查按钮绑定状态
            Console.WriteLine($"添加按钮绑定状态: {btnAddClientPrice?.Name ?? "未找到"}");
            Console.WriteLine($"产品选择按钮绑定状态: {btnSelectProduct?.Name ?? "未找到"}");
            
            // 调试：显示传递的客户单价ID
            Console.WriteLine($"传递的客户单价ID: {ClientPriceId}");
            Console.WriteLine($"传递的客户单价编号: {ClientPriceCode}");
            
            // 加载阶梯折扣数据
            await LoadLadderDiscountData();
            
            // 反填传入的数据到界面
            FillFormData();
        }

        /// <summary>
        /// 加载阶梯折扣数据
        /// </summary>
        private async Task LoadLadderDiscountData()
        {
            try
            {
                // API基础地址
                string baseUrl = "http://10.223.8.6:3530/api/Ladder/GetLadder";
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(baseUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();

                    LadderApiResponse apiResponse = JsonConvert.DeserializeObject<LadderApiResponse>(jsonResponse);
                    if (apiResponse.code == 200)
                    {
                        // 绑定数据到DataGridView
                        dgvLadder.DataSource = apiResponse.data;
                        
                        // 添加DataGridView的CellClick事件处理
                        dgvLadder.CellClick += DgvLadder_CellClick;
                        
                        // 等待DataGridView数据绑定完成后再进行自动推荐
                        dgvLadder.DataBindingComplete += (s, args) => 
                        {
                            // 调试：输出列名以便确认
                            Console.WriteLine("DataGridView列名:");
                            for (int i = 0; i < dgvLadder.Columns.Count; i++)
                            {
                                Console.WriteLine($"列 {i}: {dgvLadder.Columns[i].Name} - {dgvLadder.Columns[i].HeaderText}");
                            }
                            // 自动推荐合适的阶梯折扣
                            AutoRecommendLadderDiscount();
                        };
                    }
                    else
                    {
                        // 显示错误信息
                        MessageBox.Show($"查询失败{apiResponse.msg}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载阶梯折扣数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 反填传入的数据到界面控件
        /// </summary>
        private void FillFormData()
        {
            // 产品编码
            txtProductCode.Text = !string.IsNullOrEmpty(ProductCode) ? ProductCode : "";

            // 产品名称
            txtProduct.Text = !string.IsNullOrEmpty(ProductName) ? ProductName : "";

            // 产品规格型号
            txtProductSpec.Text = !string.IsNullOrEmpty(Specification) ? Specification : "";
            
            // 折扣方案名称
            txtDiscountName.Text = !string.IsNullOrEmpty(DiscountName) ? DiscountName : "";
            
            // 总金额（格式化显示）
            if (!string.IsNullOrEmpty(TotalAmount) && double.TryParse(TotalAmount, out double totalAmountValue))
            {
                txtTotalAmount.Text = totalAmountValue.ToString("F2");
            }
            else
            {
                txtTotalAmount.Text = "0.00";
            }
            
            // 设置创建日期
            if (!string.IsNullOrEmpty(ClientPriceCode))
            {
                // 如果有客户单价编号，说明是修改现有记录，使用当前日期
                dateCreateDate.Value = DateTime.Now;
            }
            else
            {
                // 如果没有客户单价编号，说明是新增记录，使用当前日期
                dateCreateDate.Value = DateTime.Now;
            }
        }

        /// <summary>
        /// 产品选择按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnSelectProduct_Click(object sender, EventArgs e)
        {
            try
            {
                // 打开产品选择窗体
                SelectProduct selectProduct = new SelectProduct();
                if (selectProduct.ShowDialog() == DialogResult.OK && selectProduct.SelectedProduct != null)
                {
                    var selectedProduct = selectProduct.SelectedProduct;

                    // 更新产品相关信息显示
                    txtProduct.Text = selectedProduct.ProductName;
                    txtProductCode.Text = selectedProduct.ProductCode;
                    txtProductSpec.Text = selectedProduct.Specification;

                    // 更新产品相关属性
                    ProductName = selectedProduct.ProductName;
                    ProductCode = selectedProduct.ProductCode;
                    Specification = selectedProduct.Specification;

                    // 显示选择成功提示
                    MessageBox.Show($"已选择产品：{selectedProduct.ProductName}\n产品编码：{selectedProduct.ProductCode}\n规格型号：{selectedProduct.Specification}",
                        "产品选择", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 记录日志（可选）
                    Console.WriteLine($"产品选择更新：{selectedProduct.ProductName} - {selectedProduct.ProductCode}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择产品时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 安全获取DataGridView列值的方法
        /// </summary>
        /// <param name="row">DataGridView行对象</param>
        /// <param name="columnIndex">列索引</param>
        /// <returns>列值字符串</returns>
        private string GetCellValue(DataGridViewRow row, int columnIndex)
        {
            try
            {
                if (row != null && columnIndex >= 0 && columnIndex < row.Cells.Count)
                {
                    return row.Cells[columnIndex].Value?.ToString() ?? "";
                }
                return "";
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取列值出错: {ex.Message}");
                return "";
            }
        }

        /// <summary>
        /// 根据总金额自动推荐阶梯折扣
        /// 根据订单总金额自动选择最合适的阶梯折扣方案
        /// </summary>
        private void AutoRecommendLadderDiscount()
        {
            try
            {
                if (double.TryParse(txtTotalAmount.Text.Trim(), out double totalAmount) && totalAmount > 0)
                {
                    // 等待DataGridView数据加载完成
                    if (dgvLadder.Rows.Count > 0)
                    {
                        // 根据总金额找到最合适的阶梯折扣
                        int bestRowIndex = -1;
                        double bestRule = 0;

                        for (int i = 0; i < dgvLadder.Rows.Count; i++)
                        {
                            var row = dgvLadder.Rows[i];
                            if (row.IsNewRow) continue;

                            var ruleValue = GetCellValue(row, 1); // 第二列：阶梯折扣规则
                             Console.WriteLine($"检查规则: {ruleValue}, 总金额: {totalAmount}");
                             if (double.TryParse(ruleValue, out double rule) && rule <= totalAmount && rule > bestRule)
                            {
                                bestRule = rule;
                                bestRowIndex = i;
                            }
                        }

                        // 如果找到合适的阶梯折扣，自动选择
                        if (bestRowIndex >= 0)
                        {
                            // 模拟点击该行
                            DgvLadder_CellClick(dgvLadder, new DataGridViewCellEventArgs(0, bestRowIndex));
                            
                            // 显示推荐提示
                            MessageBox.Show($"根据总金额 {totalAmount:F2} 元，系统自动推荐了阶梯折扣方案。", 
                                "自动推荐", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 自动推荐失败不影响正常使用，只记录错误
                Console.WriteLine($"自动推荐阶梯折扣时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 阶梯折扣DataGridView选择事件
        /// 处理用户在阶梯折扣表格中的选择操作
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void DgvLadder_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.RowIndex < dgvLadder.Rows.Count)
            {
                try
                {
                    // 获取选中的阶梯折扣数据
                    var row = dgvLadder.Rows[e.RowIndex];
                    
                    // 使用安全的方法获取列值
                    var ladderId = GetCellValue(row, 0); // 第一列：阶梯折扣Id
                    var ladderRule = GetCellValue(row, 1); // 第二列：阶梯折扣规则
                    var ladderDetails = GetCellValue(row, 2); // 第三列：阶梯折扣明细
                    
                    // 调试输出
                    Console.WriteLine($"选中行数据: ID={ladderId}, Rule={ladderRule}, Details={ladderDetails}");

                    // 验证数据有效性
                    if (int.TryParse(ladderId, out int id) && 
                        !string.IsNullOrEmpty(ladderRule) && 
                        !string.IsNullOrEmpty(ladderDetails))
                    {
                        // 更新属性
                        SelectedLadderId = id;
                        SelectedLadderRule = ladderRule;
                        SelectedLadderDetails = ladderDetails;

                        // 填充折扣选择字段 - 只显示ID
                        txtLadderId.Text = id.ToString();

                        // 计算折扣金额
                        CalculateDiscountAmount();

                        // 高亮显示选中的行
                        dgvLadder.ClearSelection();
                        dgvLadder.Rows[e.RowIndex].Selected = true;

                        // 显示选择成功提示
                        MessageBox.Show($"已选择阶梯折扣：\nID: {id}\n规则: {ladderRule}\n折扣率: {ladderDetails}%", 
                            "阶梯折扣选择", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("阶梯折扣数据格式不正确，请重新选择", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"选择阶梯折扣时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 计算折扣金额
        /// 根据总金额和折扣率计算实际的折扣金额
        /// </summary>
        private void CalculateDiscountAmount()
        {
            try
            {
                // 获取总金额
                if (double.TryParse(txtTotalAmount.Text.Trim(), out double totalAmount) &&
                    double.TryParse(SelectedLadderDetails, out double discountRate))
                {
                    // 计算折扣金额：总金额 * (1 - 折扣率/100)
                    // 例如：折扣率98%表示打98折，实际支付98%
                    double discountAmount = totalAmount * (1 - discountRate / 100);
                    
                    // 显示折扣金额（保留两位小数）
                    txtDiscountAmount.Text = discountAmount.ToString("F2");
                }
                else
                {
                    txtDiscountAmount.Text = "0.00";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"计算折扣金额时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtDiscountAmount.Text = "0.00";
            }
        }

        /// <summary>
        /// 添加折扣方案按钮点击事件
        /// 保存折扣方案到数据库
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void btnAddDiscount_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrEmpty(txtDiscountName.Text.Trim()))
                {
                    MessageBox.Show("请输入折扣方案名称");
                    return;
                }

                if (string.IsNullOrEmpty(txtProductCode.Text.Trim()))
                {
                    MessageBox.Show("请选择产品");
                    return;
                }

                if (SelectedLadderId <= 0)
                {
                    MessageBox.Show("请选择阶梯折扣方案");
                    return;
                }

                // 创建折扣方案数据对象
                var discountData = new
                {
                    DiscountName = txtDiscountName.Text.Trim(),//折扣方案
                    ProductCode = txtProductCode.Text.Trim(),//产品名称
                    ProductName = txtProduct.Text.Trim(),//产品
                    Specification = txtProductSpec.Text.Trim(),//规格型号
                    TotalAmount = txtTotalAmount.Text.Trim(),//总金额
                    CreateDate = dateCreateDate.Value.ToString("yyyy-MM-dd"),//日期
                    ClientPriceId = ClientPriceId,//客户单价ID
                    ClientPriceCode = ClientPriceCode ?? "",//编号
                    DiscountAmount = txtDiscountAmount?.Text?.Trim() ?? "",
                    LadderId = SelectedLadderId,//阶梯折扣ID
                    LadderRule = SelectedLadderRule ?? "",//阶梯折扣规则
                    LadderDetails = SelectedLadderDetails ?? "",//阶梯折扣明细
                    DiscountSelection = txtLadderId?.Text?.Trim() ?? ""//折扣选择ID
                };

                // 转换为JSON
                string jsonData = JsonConvert.SerializeObject(discountData);

                // 调用API添加折扣方案
                string apiUrl = "http://10.223.8.6:3530/api/Discount/UpdateDiscount";
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);
                    string jsonResponse = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        dynamic result = JsonConvert.DeserializeObject(jsonResponse);
                        if (result != null && result.code == 200)
                        {
                            // 显示添加成功提示
                            MessageBox.Show("折扣方案添加成功！", "添加成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 直接设置返回结果，通知父窗体需要刷新折扣方案列表并跳转
                            this.DialogResult = DialogResult.OK;
                            this.Tag = "RefreshDiscountList"; // 标记需要刷新折扣方案列表
                            this.Close();
                        }
                        else
                        {
                            MessageBox.Show("添加失败: " + (result?.msg ?? jsonResponse), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"添加失败：{response.StatusCode}\n{jsonResponse}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加折扣方案时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 清空输入框
        /// 重置所有输入控件到初始状态
        /// </summary>
        private void ClearInputs()
        {
            txtDiscountName.Text = "";
            txtProductCode.Text = "";
            txtProduct.Text = "";
            txtProductSpec.Text = "";
            txtTotalAmount.Text = "0.00";
            txtDiscountAmount.Text = "0.00";
            txtLadderId.Text = "";
            dateCreateDate.Value = DateTime.Now;
            
            // 清空选中的阶梯折扣
            SelectedLadderId = 0;
            SelectedLadderRule = "";
            SelectedLadderDetails = "";
            
            // 清除表格选择
            if (dgvLadder.Rows.Count > 0)
            {
                dgvLadder.ClearSelection();
            }
        }

        /// <summary>
        /// 添加客户单价按钮点击事件（保留方法，实际调用btnAddDiscount_Click）
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnAddClientPrice_Click(object sender, EventArgs e)
        {
            // 此方法保留是为了兼容性，实际功能由btnAddDiscount_Click实现
        }
    }
}
